//首页 main.html
app.controller('mainCtrl', function ($scope, $http, $location) {
  //页面通用初始化
  pageInit('main');
  //初始化
  $http.get('/deploy/main/init').then(function (response) {
    $scope.apps = apps;
    if (response.status == 200) {
      var message = response.data;
      if (message.code == 0) {
        var data = message.data.bean;
        //单选框
        $scope.databaseSchema = data.databaseSchema;
        //多选框
        var deployApps = data.deployApps ? data.deployApps : [];
        for (var i = 0; i < deployApps.length; i++) {
          apps[deployApps[i]].sel = true;
        }
      } else {
        $.showNotice(message.msg, "danger");
      }
    }
  }).catch(function (response) {
    $.showNotice(response.status + " error：" + response.data.message, "danger");
  });
  //方法
  $scope.radio = function (index) {
    $scope.databaseSchema = index;
  };
  // 调度1.0和2.0不能被同时选中的处理
  /* $scope.checkbox = function (index) {
    if (index == 0 && apps[1].sel == true) {
      apps[1].sel = false;
    } else if (index == 1 && apps[0].sel == true) {
      apps[0].sel = false;
    }
  }; */
  //提交
  $scope.deploy = function (dispatcher) {

    //处理参数
    var deployApps = [];
    for (var i = 0; i < apps.length; i++) {
      if (apps[i].sel == true) deployApps.push(i);
    }

    if (!dispatcher) {
      // 全部不勾选
      if (!apps[0].sel && !apps[1].sel) {
        $.showNotice("[调度1.0] 和 [调度2.0] 至少需要勾选一个！", "danger");
        return;
      }
      // 全部勾选
      if (apps[0].sel && apps[1].sel) {
        $('#main-confirm').modal('show');
        return;
      }
      deploy(-1);
    } else {
      $('#main-confirm').modal('hide');
      $('#main-confirm').on('hidden.bs.modal', function (e) {
        deploy(dispatcher);
      })
    }

    //部署
    function deploy(dispatcher) {
      if ($scope.loadingNext) return;
      $scope.loadingNext = true;
      $http.post('/deploy/main/submit', {
        databaseSchema: $scope.databaseSchema,
        deployApps: deployApps,
        dispatcher: dispatcher
      }).then(function (response) {
        $scope.loadingNext = false;
        if (response.status == 200) {
          var message = response.data;
          if (message.code == 0) {
            var data = message.data;
            if ($scope.databaseSchema == 0)
              $location.path('database');
            if ($scope.databaseSchema == 1)
              $location.path('database-multi');
          } else {
            $.showNotice(message.msg, "danger");
          }
        }
      }).catch(function (response) {
        $scope.loadingNext = false;
        $.showNotice(response.status + " error：" + response.data.message, "danger");
      });
    }

  };
});